import React from 'react';
import MUtil from 'util/mm.jsx'
import User from 'service/user-service.jsx'
const _mm = new MUtil()
const _user = new User()
import './index.scss';

class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            redirect: _mm.getUrlParam('redirect') || '/'
        }
    }

    onInputChange(e) {
        let inputValue = e.target.value,
            inputName = e.target.name
        this.setState({
            [inputName]: inputValue
        })
    }

    omInputKeyUp(e) {
        if(e.keyCode == 13) {
            this.onSubmit()
        }
    }

    onSubmit() {
        let logInfo = {
            username: this.state.username,
            password: this.state.password
        },
        checkResult = _user.checkLoginInfo(logInfo);
        if(checkResult.status) {
            _user.login(logInfo).then((res) => {
                _mm.setStorage('userInfo', res)
                this.props.history.push(this.state.redirect)
            }, (errMsg) => {
                _mm.errorTips(errMsg)
            })
        }
        else {
            _mm.errorTips(checkResult.msg)
        }
       
    }

    render() {
        return (
            <div className="col-md-4 col-md-offset-4">
                <div className="panel panel-default login-panel">
                    <div className="panel-heading">欢迎登陆 - MMALL</div>
                    <div className="panel-body">
                        <div>
                            <div className="form-group">
                                <input type="text" name="username" className="form-control" onKeyUp={e => {this.omInputKeyUp(e)}} onChange={e => this.onInputChange(e)} placeholder="请输入用户名"/>
                            </div>
                            <div className="form-group">
                                <input type="password" name="password" className="form-control" onKeyUp={e => {this.omInputKeyUp(e)}} onChange={e => this.onInputChange(e)} placeholder="请输入密码"/>
                            </div>
                            <button className="btn btn-primary btn-block" onClick={(e)=> {this.onSubmit(e)}}>Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default Home;